﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using ZLDC.Common.Estate;
using ZLDC.Topo.Model.Estate;
using ZLDC.Topo.BLL.Estate;
using System.Data;
using System.Collections;

namespace ZLDC.Estate.PM
{
    public partial class HousingDetail : _PageBase
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {


                ddept.Value = this.info.m_sDeptName;
                ddeptid.Value = this.info.m_sDeptID;
                duser.Value = this.info.m_sUserName;
                duserid.Value = this.info.m_sUserID;

                int id = _Request.GetInt("id", 0);//盘源ID

                if (id == 0)
                {
                    _JavaScript.Alert(this.Page, "盘源编号有误");
                    return;
                }

                HousingInfo info = CacheHousing.Cache_Detail_Info(id);

                if (info != null)
                {
                    fprice.Value = info.Totalprice.ToString();//最近总价

                    funitprice.Value = info.Leaseprice.ToString();//最近租价
                    fImportant.Value = info.Mark5.ToString();//重要备注;
                    string tradetype = info.TradeType.ToString();
                    if (tradetype == "1")
                    {
                        divRent.Visible = false;
                    }
                    else
                    {
                        divSale.Visible = false;
                    }
                    span_linkmantel.InnerHtml = info.LinkmanTel;//代理人电话
                    span_ownertel.InnerHtml = info.OwnerTel;//业主电话   
                    spanowner1.InnerHtml = info.Owner;//业主姓名
                    spanlinkman1.InnerHtml = info.Linkman;//代理人

                }
                ZLDC.Topo.BLL.Estate.SystemParamBLL.LoadParamType(followType, false, "跟进方式");

                btnCompetences();   // 权限控制按钮

                setUrl();

                hAllowPhotoCount.Value = "5";// ZLDC.Topo.BLL.Estate.SystemOptionBLL.GetOption("盘源允许上传室内图数").ToString();
                if (info != null)
                {
                    LoadAppliances(info.HAppliances);///加载房屋设施
                    hIsLock.Value = info.Protected.ToString();///是否封盘0，不是，1是
                }

                string allchildrenDept = _Utility.GetInfoBySession().m_sChildrenDeptList; //所有下级本门
                ///封盘人，本部门管理者，系统管理员
                if (info.Protected.ToString() == "1")
                {
                    if (info.ProtectedUid.ToString() == _Utility.GetInfoBySession().m_sUserID || allchildrenDept.Contains(info.MarkUDeptId.ToString()) || ZLDC.Common.BaseUser.UserInfo.GetPopedom("查看全部盘源"))
                    {
                        hStation.Value = _Utility.GetInfoBySession().m_sStation;//岗位状态

                        hProtectedClass.Value = ZLDC.Topo.BLL.Estate.HousingExtendBLL.p_Housing_Extend_List(id);///封盘查看业主电话权限
                    }
                }

            }
        }

        // 权限控制按钮
        private void btnCompetences()
        {
            int id = _Request.GetInt("id", 0);      // 盘源ID
            int userid = _Convert.ToInt(duserid.Value, 0);
            string deptid = this.info.m_sDeptID;
            string station = this.info.m_sStation;   //_Utility.GetUserStation(userid);   // 职称

            if (id <= 0)
                return;

            HousingInfo info = CacheHousing.Cache_Detail_Info(id);
            if (info == null)
                return;

            // 开盘人电话                                                    
            if (info != null)
            {
                string tel = "";    // 开盘人电话
                string mobile = ""; // 开盘人手机
                UserBLL.GetUserInfo(info.MarkUId, ref tel, ref mobile);
                if (tel == "" && mobile == "")
                {
                    sMarkTel.InnerText = "";
                }
                sMarkTel.InnerHtml = "&nbsp;&nbsp;电话:" + tel;
                if (mobile != "")
                {
                    sMarkTel.InnerHtml += " [短号:" + mobile + "]";
                }

                span_ownertel.InnerHtml = info.OwnerTel;//业主电话
                span_linkmantel.InnerHtml = info.LinkmanTel;//代理人电话
            }
            string RecommendUid = "";
            HousingEverydayInfo hinfo = ZLDC.Topo.BLL.Estate.HousingEverydayBLL.SelectHousingEveryDays(id, 1);

            RecommendUid = hinfo.UserId.ToString();//推荐人ID;

            if (RecommendUid == _Utility.GetInfoBySession().m_sUserID && info.Recommend.ToString() == "1")
            {
                btnRecommend.Text = "取消推荐";
            }
            string allchildrenDept = _Utility.GetInfoBySession().m_sChildrenDeptList; //所有下级本门

            ///封盘人，本部门管理者，系统管理员
            if (info.Protected.ToString() == "1" && (info.ProtectedUid.ToString() == _Utility.GetInfoBySession().m_sUserID || allchildrenDept.Contains(info.MarkUDeptId.ToString()) || ZLDC.Common.BaseUser.UserInfo.GetPopedom("查看全部盘源")))
            {
                btnLock.Text = "取消封盘";
            }

            // status 1 当前盘 2 资料盘 3 无效盘 status1 0 正常 1 成交封盘 2 资料盘转当前盘 3 垃圾盘转当前盘  isvalid 0有效 1待审核 2无效  Protected 0未封盘保护 1已封盘保护
            if (info.Status1 < 2 && info.Protected == 0)
            {
                // status 1当前盘 2资料盘 3无效盘
                if (info.Status == 1)
                {
                    // 置业顾问可转自己的当前盘，经理可以转本组的
                    if (_Utility.GetWebConfigSetting("SalesManagerStation").Contains(station))
                    {
                        string deptlist = CacheUtility.Cache_GetAllChildDept(deptid.ToString());
                        if (deptlist.Contains(info.MarkUDeptId.ToString()))
                        {
                            btnStatus1.Visible = true;          // 转资料
                            btnStatus3.Visible = true;          // 转无效
                        }
                    }
                    else if (info.MarkUId == userid)
                    {
                        btnStatus1.Visible = true;          // 转资料
                        btnStatus3.Visible = true;          // 转无效
                    }
                }
                else if (info.Status == 2)
                {
                    btnStatus3.Visible = true;          // 转无效
                    if (_Utility.GetWebConfigSetting("SalesManagerStation").Contains(station))
                    {
                        btnStatus2.Visible = false;     // 申请转到当前                    
                        btnStatus4.Visible = true;      // 转到当前盘，选择开盘人                        
                    }
                    else if (ZLDC.Common.BaseUser.UserInfo.GetPopedom("转盘待审"))
                    {
                        btnStatus2.Visible = false;
                        btnStatus4.Visible = true;      // 转到当前盘，选择开盘人                        
                    }
                    else
                    {
                        btnStatus2.Visible = true;      // 申请转到当前
                        btnStatus4.Visible = false;     // 转到当前盘，选择开盘人
                    }

                    // 如果是资料盘，则不允许推荐笋盘或每日一盘
                    btnRecommend.Visible = false;       // 推荐
                    btnEveryday.Visible = false;        // 每日一盘
                }
                else if (info.Status == 3)
                {
                    btnStatus1.Visible = true;          // 转资料
                    if (_Utility.GetWebConfigSetting("SalesManagerStation").Contains(station))
                    {
                        btnStatus2.Visible = false;     // 申请转到当前                       
                        btnStatus4.Visible = true;      // 转到当前盘，选择开盘人                       
                    }
                    else
                    {
                        btnStatus2.Visible = true;      // 申请转到当前
                        btnStatus4.Visible = false;     // 转到当前盘，选择开盘人
                    }

                    // 如果是资料盘，则不允许推荐笋盘或每日一盘
                    btnRecommend.Visible = false;       // 推荐
                    btnEveryday.Visible = false;        // 每日一盘
                }
            }
            else
            {
                btnStatus1.Visible = false;     // 转资料
                btnStatus2.Visible = false;     // 申请转当前
                btnStatus3.Visible = false;     // 转无效

                btnEveryday.Visible = false;    // 每日一盘
                btnRecommend.Visible = false;   // 推荐
                btnLock.Visible = false;        // 封盘
            }

            // 权限判断
            if (!ZLDC.Common.BaseUser.UserInfo.GetPopedom("转资料"))
                btnStatus1.Visible = false;
            if (!ZLDC.Common.BaseUser.UserInfo.GetPopedom("转当前"))
                btnStatus2.Visible = false;
            if (!ZLDC.Common.BaseUser.UserInfo.GetPopedom("转无效"))
                btnStatus3.Visible = false;

            if (ZLDC.Common.BaseUser.UserInfo.GetPopedom("添加跟进"))
                //HLAddFollow.Visible = true;
                btnOK.Visible = true;
            if (ZLDC.Common.BaseUser.UserInfo.GetPopedom("删除跟进"))
                HLDelFollow.Visible = true;
            if (ZLDC.Common.BaseUser.UserInfo.GetPopedom("上传图片"))
                hCompetencesIsUploadPic.Value = "1";
            if (ZLDC.Common.BaseUser.UserInfo.GetPopedom("删除本部图片"))
                hCompetencesIsDelPic.Value = "1";
            if (ZLDC.Common.BaseUser.UserInfo.GetPopedom("删除图片"))
                hCompetencesAllIsDelPic.Value = "1";
            if (ZLDC.Common.BaseUser.UserInfo.GetPopedom("删除提醒"))
                HLDelAlert.Visible = true;
            if (ZLDC.Common.BaseUser.UserInfo.GetPopedom("处理提醒"))
                HLUpdateAlert.Visible = true;

            if (ZLDC.Common.BaseUser.UserInfo.GetPopedom("借钥匙登记"))
                HLShowKey.Visible = true;

            if (ZLDC.Common.BaseUser.UserInfo.GetPopedom("查看电话"))
                hCompetencesIsShowTel.Value = "1";

            if (ZLDC.Common.BaseUser.UserInfo.GetPopedom("添加举报"))
                btnInfo.Visible = true;
            if (ZLDC.Common.BaseUser.UserInfo.GetPopedom("删除盘源"))
                btnDelete.Visible = true;
            if (ZLDC.Common.BaseUser.UserInfo.GetPopedom("推荐"))
                btnRecommend.Visible = true;
            if (ZLDC.Common.BaseUser.UserInfo.GetPopedom("收藏"))
                btnFavorite.Visible = true;
            if (ZLDC.Common.BaseUser.UserInfo.GetPopedom("封盘"))
                btnLock.Visible = true;

            // 1分行经理及以上级别
            string SalesManagerStation = _Utility.GetWebConfigSetting("SalesManagerStation");
            if (SalesManagerStation.Contains(this.info.m_sStation))
                hCompetencesIsSalesManagerStation.Value = "1";

            //转成交盘权限
            if (info.TradeType.ToString() == "1" && info.IsValid == 0)
            {
                //成交盘 MarkUDeptId 管理员或者直接本部门经理 通过授权
                if ((info.MarkUDeptId.ToString() == _Utility.GetInfoBySession().m_sDeptID && ZLDC.Common.BaseUser.UserInfo.GetPopedom("转成交盘")) || ZLDC.Common.BaseUser.UserInfo.GetPopedom("转所有成交盘"))
                {
                    this.btnOver.Visible = true;

                }
                else if (SalesManagerStation.Contains(_Utility.GetInfoBySession().m_sStation))//区域经理
                {
                    string GetParentIdById = ZLDC.DAL.Estate.DeptDAL.GetParentIdById(info.MarkUDeptId);

                    if (GetParentIdById == _Utility.GetInfoBySession().m_sDeptID && ZLDC.Common.BaseUser.UserInfo.GetPopedom("转成交盘"))
                    {
                        this.btnOver.Visible = true;
                    }

                }

                if (info.Status1 == 1)
                {
                    this.btnOver.Text = "取消成交";
                }

            }
            if (RecommendUid != _Utility.GetInfoBySession().m_sUserID && info.Recommend.ToString() == "1")//如果不是本人，则不能取消推荐
            {
                btnRecommend.Visible = false;
            }

            // 信息技术部权限全部开通
            if (_Utility.GetInfoBySession().m_sDeptName.Contains("信息技术部"))
            {
                btnStatus1.Visible = true;          // 转资料
                btnStatus3.Visible = true;          // 转无效
                btnDelete.Visible = true;           // 删除
                btnLock.Visible = true;             // 封盘
                btnStatus4.Visible = true;//转当前
            }






            //封盘人或者本部门管理人员才有取消封盘权限
            if (!ZLDC.Common.BaseUser.UserInfo.GetPopedom("查看全部盘源"))//管理员拥有最高权限
            {
                isManager.Value = "";
                if (info.ProtectedUid.ToString() != this.info.m_sUserID && !allchildrenDept.Contains(info.MarkUDeptId.ToString()) && info.Protected == 1)
                {
                    this.btnLock.Visible = false;
                }
            }
        }

        // 申请转到当前盘
        protected void btnStatus2_Click(object sender, EventArgs e)
        {
            #region   早9点到晚23之外的时间不能转为当前盘

            int bTime = _Convert.ToInt(ZLDC.Topo.BLL.Estate.SystemOptionBLL.GetOption("资料盘转当前盘时间限定1").ToString());
            int eTime = _Convert.ToInt(ZLDC.Topo.BLL.Estate.SystemOptionBLL.GetOption("资料盘转当前盘时间限定2").ToString());

            if (DateTime.Now.Hour < bTime || DateTime.Now.Hour >= eTime)
            {
                _JavaScript.Alert(this.Page, "当前时间段不能申请转盘！");
                return;
            }

            #endregion

            int id = _Convert.ToInt(hID.Value, 0);

            if (id <= 0)
            {
                _JavaScript.Alert(this.Page, "请先选择您要操作的盘源");
                return;
            }

            string outmsg = ZLDC.Topo.BLL.Estate.HousingBLL.p_housing_isupdatemark(id);
            if (outmsg != "")
            {
                _JavaScript.Alert(this.Page, outmsg);
                return;
            }

            outmsg = ZLDC.Topo.BLL.Estate.HousingBLL.HousingStatus(id, 1, "");
            if (outmsg != "")
            {
                // 更新开盘人及开盘人部门信息
                int markUid = _Convert.ToInt(_Utility.GetInfoBySession().m_sUserID, 0);
                string markUser = _Utility.GetInfoBySession().m_sUserName;
                int markUdeptid = _Convert.ToInt(_Utility.GetInfoBySession().m_sDeptID, 0);
                string markUdept = _Utility.GetInfoBySession().m_sDeptName;

                ZLDC.Topo.BLL.Estate.HousingBLL.UpdateMark(id, markUid, markUser, markUdeptid, markUdept);

                _JavaScript.Alert(this.Page, outmsg);
            }

            // 更新缓存
            if (id > 0)
            {
                _Cache.Remove(CacheConst.CACHE_HOUSING_DETAIL_JSON + id.ToString());
                _Cache.Remove(CacheConst.CACHE_HOUSING_DETAIL_INFO + id.ToString());
                _Cache.RemoveLike(CacheConst.CACHE_HOUSING_FOLLOW_JSON + id);
            }

            btnCompetences();   // 权限控制按钮
        }

        /// <summary>
        /// 转到当前盘(指定开盘人)
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btToPty_Click(object sender, System.EventArgs e)
        {
            #region   早9点到晚23之外的时间不能转为当前盘

            int bTime = _Convert.ToInt(ZLDC.Topo.BLL.Estate.SystemOptionBLL.GetOption("资料盘转当前盘时间限定1").ToString());
            int eTime = _Convert.ToInt(ZLDC.Topo.BLL.Estate.SystemOptionBLL.GetOption("资料盘转当前盘时间限定2").ToString());

            if (DateTime.Now.Hour < bTime || DateTime.Now.Hour >= eTime)
            {
                _JavaScript.Alert(this.Page, "当前时间段不能转盘！");
                return;
            }

            #endregion


            int id = _Convert.ToInt(hID.Value, 0);

            if (id <= 0)
            {
                _JavaScript.Alert(this.Page, "请先选择您要操作的盘源");
                return;
            }

            string userNoAndName = tbMakeUser.Text;      // 工号及名称

            if (userNoAndName.Trim().Equals(""))
            {
                _JavaScript.Alert(this.Page, "开盘人不能为空");
                return;
            }

            string userName = string.Empty; // 姓名
            string userNo = string.Empty;   // 工号
            int userId = 0;                 // 楼盘系统用户ID
            _Utility.GetUserNoAndUserName(userNoAndName.Trim(), out userName, out userNo);
            userId = ZLDC.Topo.BLL.Estate.UserBLL.GetUserIDByUserName(userName, userNo);

            if (userId == 0)
            {
                _JavaScript.Alert(this, "该用户不存在，请先登录!");
                return;
            }

            // 更新开盘人及开盘人部门信息
            UserInfo userinfo = ZLDC.Topo.BLL.Estate.UserBLL.GetUserInfoByUserID(userId);

            int deptid = userinfo.Dept_id;
            string deptname = userinfo.DeptName;
            int userid = userinfo.Id;
            string username = userinfo.Name;

            ZLDC.Topo.BLL.Estate.HousingBLL.HousingStatusPty(id, userid, username, deptid, deptname);

            if (id > 0)
            {
                // 盘源详细信息
                HousingInfo info = HousingBLL.p_housing_detail(id);
                //1转盘通过 计入量化

                int isadd = 0;
                int isadd1 = 0;
                if (info.TradeType == 1)
                {
                    isadd = 1;
                }
                else if (info.TradeType == 2)
                {
                    isadd1 = 1;
                }
                quantificationBLL.UpdateHousingQuantification(id, userid, deptid, deptname, username, isadd, 0, 0, 0, 0, isadd1);
            }

            // 更新缓存
            if (id > 0)
            {
                _Cache.Remove(CacheConst.CACHE_HOUSING_DETAIL_JSON + id.ToString());
                _Cache.Remove(CacheConst.CACHE_HOUSING_DETAIL_INFO + id.ToString());
                _Cache.RemoveLike(CacheConst.CACHE_HOUSING_FOLLOW_JSON + id);
            }
        }

        // 设置 首条 上一条 下一条 尾条 
        private void setUrl()
        {
            string id = _Request.GetString("id");               // 当前ID
            string id_list = _Request.GetString("id_list");     // 所有ID字符串
            string tagNo = _Request.GetString("tagNo");

            if (id_list.IndexOf(",") < 0)
            {
                btnFirst.Visible = false;
                btnPrev.Visible = false;
                btnNext.Visible = false;
                btnLast.Visible = false;

                return;
            }

            string[] m_sIdiList = id_list.Split(',');   // 所有ID数组
            int m_nPos = 0;

            //检查位置
            int listLength = m_sIdiList.Length;
            for (int i = 0; i < listLength; i++)
            {
                if (m_sIdiList[i] == id)
                {
                    m_nPos = i;
                    break;
                }
            }

            this.btnFirst.Attributes["onclick"] = "javascript:window.location.href='HousingDetail.aspx?tagNo=" + tagNo + "&id=" + m_sIdiList[0] + "&id_list=" + id_list + "';return false;";
            if (m_nPos != 0)
            {
                this.btnPrev.Enabled = true;
                this.btnFirst.Enabled = true;
                this.btnPrev.Attributes["onclick"] = "javascript:window.location.href='HousingDetail.aspx?tagNo=" + tagNo + "&id=" + m_sIdiList[m_nPos - 1] + "&id_list=" + id_list + "';return false;";
            }
            else
            {
                this.btnPrev.Enabled = false;
                this.btnFirst.Enabled = false;
            }
            if (m_nPos != m_sIdiList.Length - 1)
            {
                this.btnNext.Enabled = true;
                this.btnLast.Enabled = true;
                this.btnNext.Attributes["onclick"] = "javascript:window.location.href='HousingDetail.aspx?tagNo=" + tagNo + "&id=" + m_sIdiList[m_nPos + 1] + "&id_list=" + id_list + "';return false;";
            }
            else
            {
                this.btnNext.Enabled = false;
                this.btnLast.Enabled = false;
            }
            this.btnLast.Attributes["onclick"] = "javascript:window.location.href='HousingDetail.aspx?tagNo=" + tagNo + "&id=" + m_sIdiList[m_sIdiList.Length - 1] + "&id_list=" + id_list + "';return false;";
        }

        protected void btnOver_Click(object sender, EventArgs e)
        {
            int id = _Request.GetInt("id", 0);      // 盘源ID
            string outmsg = ZLDC.Topo.BLL.Estate.HousingBLL.UpdateStatus1(id);
            //添加跟进记录
            ZLDC.Topo.BLL.Estate.HousingFollowBLL.p_housingFollow_save(0, id, "", _Convert.ToInt(_Utility.GetInfoBySession().m_sDeptID), _Utility.GetInfoBySession().m_sDeptName, _Convert.ToInt(_Utility.GetInfoBySession().m_sUserID), _Utility.GetInfoBySession().m_sUserName, "[取消成交盘]", 0, "");
            Page.ClientScript.RegisterStartupScript(this.GetType(), "msg", "alert('" + outmsg + "');");


            // 更新缓存
            if (id > 0)
            {
                _Cache.Remove(CacheConst.CACHE_HOUSING_DETAIL_JSON + id.ToString());
                _Cache.Remove(CacheConst.CACHE_HOUSING_DETAIL_INFO + id.ToString());
                _Cache.RemoveLike(CacheConst.CACHE_HOUSING_FOLLOW_JSON + id);
            }

        }

        protected void btnRecommend_Click(object sender, EventArgs e)
        {
            int id = _Request.GetInt("id", 0);
            string outmsg = ZLDC.Topo.BLL.Estate.HousingEverydayBLL.HousingEverydayRecommendDelete(id, 1);
            Page.ClientScript.RegisterStartupScript(this.GetType(), "msg", "alert('" + outmsg + "');");

        }

        /// <summary>
        /// 加载房屋设施
        /// </summary>
        /// <param name="appliances"> 如：0，1，1，0，0，....</param>
        public void LoadAppliances(string appliances)
        {
            if (appliances == "")
                return;

            DataTable dt = null;
            int total = 0;
            string condition = " where type='房屋设施'";

            using (_Database db = new _Database("estate"))
            {
                dt = ZLDC.DAL.Estate.SystemParamDAL.p_system_param_list_table(1, 50, condition, ref total, db);
            }

            string[] arr = appliances.Split(',');
            string html = "";
            for (var i = 0; i < dt.Rows.Count; i++)
            {
                if (arr[i].ToString() == "1")
                {
                    html += dt.Rows[i]["item"].ToString() + "&nbsp;&nbsp;";
                }

            }

            sAppliances.InnerHtml = html;
        }

    }
}
